import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/todo_item.dart';
import '../services/api_service.dart';
import '../services/local_cache_service.dart';

/// iOS详情页面
class TodoDetailPage extends StatefulWidget {
  final TodoItem? todo; // null表示创建模式
  final Function(TodoItem) onUpdate;
  final Function(TodoItem) onInsert;
  final String? categoryId; // 创建时的分类ID

  const TodoDetailPage({
    super.key,
    required this.todo,
    required this.onUpdate,
    required this.onInsert,
    this.categoryId,
  });

  @override
  State<TodoDetailPage> createState() => _TodoDetailPageState();
}

class _TodoDetailPageState extends State<TodoDetailPage> with WidgetsBindingObserver {
  late TextEditingController _contentController;
  late FocusNode _contentFocusNode;
  Timer? _localSaveTimer;
  static const Duration _localSaveDuration = Duration(milliseconds: 300);
  bool _isCreateMode = false;
  bool _isPreviewMode = true; // 添加预览模式状态，默认为true
  TodoItem? _currentTodo;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _isCreateMode = widget.todo == null;
    _currentTodo = widget.todo;
    _contentController = TextEditingController(text: widget.todo?.content ?? '');
    _contentFocusNode = FocusNode();
    _contentController.addListener(_onTextChanged);
    _contentFocusNode.addListener(_onFocusChanged);
    // 创建模式下自动获得焦点
    if (_isCreateMode) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _contentFocusNode.requestFocus();
      });
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _localSaveTimer?.cancel();
    _contentController.removeListener(_onTextChanged);
    _contentFocusNode.removeListener(_onFocusChanged);
    _contentController.dispose();
    _contentFocusNode.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      _syncToServer();
    }
  }

  void _onFocusChanged() {
    if (!_contentFocusNode.hasFocus) {
      _syncToServer();
    }
  }

  Future<void> _syncToServer() async {
    final content = _contentController.text.trim();
    if (content.isEmpty) return;

    if (_isCreateMode) {
      await _autoCreate();
    } else {
      await _autoSave();
    }
  }

  void _onTextChanged() {
    final content = _contentController.text.trim();

    // 创建模式：检查是否有内容
    if (_isCreateMode) {
      if (content.isEmpty) {
        _localSaveTimer?.cancel();
        return;
      }

      // 保存到本地（延迟300ms）
      _localSaveTimer?.cancel();
      _localSaveTimer = Timer(_localSaveDuration, () {
        if (_currentTodo != null) {
          LocalCacheService.saveDraft(_currentTodo!.id, content);
        }
      });
      return;
    }

    // 编辑模式：检查是否有改变
    if (_currentTodo == null) return;

    final hasChanges = content != (_currentTodo!.content ?? '');

    if (!hasChanges) {
      _localSaveTimer?.cancel();
      return;
    }

    // 保存到本地（延迟300ms）
    _localSaveTimer?.cancel();
    _localSaveTimer = Timer(_localSaveDuration, () {
      LocalCacheService.saveDraft(_currentTodo!.id, content);
    });
  }

  Future<void> _autoCreate() async {
    if (!_isCreateMode) return;

    final content = _contentController.text.trim();
    if (content.isEmpty) return;

    // 使用第一行作为标题
    final lines = content.split('\n');
    final title = lines.first.trim();
    if (title.isEmpty) return;

    final tempId = _currentTodo?.id;

    try {
      final newTodo = await ApiService.createTodo(
        title,
        content,
        categoryId: widget.categoryId,
      );

      if (mounted) {
        setState(() {
          _currentTodo = newTodo;
          _isCreateMode = false;
        });

        // 通知父页面插入新待办
        widget.onInsert(newTodo);

        // 同步成功，删除本地缓存
        if (tempId != null) {
          await LocalCacheService.deleteDraft(tempId);
        }
      }
    } catch (e) {
      // 静默失败
    }
  }

  Future<void> _autoSave() async {
    if (_currentTodo == null) return;

    final content = _contentController.text.trim();
    if (content.isEmpty) return;

    // 使用第一行作为标题
    final lines = content.split('\n');
    final title = lines.first.trim();
    if (title.isEmpty) return;

    final todoId = _currentTodo!.id;

    try {
      final updatedTodo = await ApiService.updateTodo(
        todoId,
        title,
        content,
      );

      if (mounted) {
        setState(() {
          _currentTodo = updatedTodo;
        });

        // 通知父页面更新
        widget.onUpdate(updatedTodo);

        // 同步成功，删除本地缓存
        await LocalCacheService.deleteDraft(todoId);
      }
    } catch (e) {
      // 静默失败
    }
  }

  Future<void> _onToggleTop(bool isTop) async {
    if (_currentTodo == null) return;

    final todoId = _currentTodo!.id;

    try {
      final updatedTodo = await ApiService.toggleTop(todoId, isTop);

      if (mounted) {
        setState(() {
          _currentTodo = updatedTodo;
        });

        // 通知父页面更新
        widget.onUpdate(updatedTodo);
      }
    } catch (e) {
      // 显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('操作失败: $e')),
        );
      }
    }
  }

  /// 切换关注状态
  Future<void> _toggleFavorite() async {
    if (_currentTodo == null) return;

    final todoId = _currentTodo!.id;
    final newFavoriteState = !_currentTodo!.isFavorite;

    try {
      final updatedTodo = await ApiService.updateFavorite(todoId, newFavoriteState);

      if (mounted) {
        setState(() {
          _currentTodo = updatedTodo;
        });

        // 通知父页面更新
        widget.onUpdate(updatedTodo);
      }
    } catch (e) {
      // 显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('更新关注状态失败: $e')),
        );
      }
    }
  }

  Future<void> _onDelete() async {
    if (_currentTodo == null) return;

    // 提取第一行作为显示标题
    String displayTitle = '无标题';
    if (_currentTodo!.content != null && _currentTodo!.content!.isNotEmpty) {
      final lines = _currentTodo!.content!.split('\n');
      final firstLine = lines.first.trim();
      if (firstLine.isNotEmpty) {
        displayTitle = firstLine;
      }
    }

    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除待办"$displayTitle"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    final todoId = _currentTodo!.id;

    try {
      await ApiService.deleteTodo(todoId);

      if (mounted) {
        // 删除本地缓存
        await LocalCacheService.deleteDraft(todoId);

        // 返回上一页（通过pop告诉父页面需要刷新列表）
        if (mounted) {
          Navigator.pop(context);
        }
      }
    } catch (e) {
      // 显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除失败: $e')),
        );
      }
    }
  }

  /// 处理链接点击
  Future<void> _handleLinkTap(String text, String? href, String title) async {
    if (href == null) return;

    final uri = Uri.tryParse(href);
    if (uri == null) return;

    try {
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      }
    } catch (e) {
      // 静默失败
    }
  }

  /// 提取第一行作为标题
  String _getTitle() {
    if (_isCreateMode) {
      return '新建待办';
    }

    if (_currentTodo?.content == null || _currentTodo!.content!.isEmpty) {
      return '待办详情';
    }

    final lines = _currentTodo!.content!.split('\n');
    final firstLine = lines.first.trim();
    return firstLine.isEmpty ? '待办详情' : firstLine;
  }

  /// 切换当前行的TODO标记（- [ ]）
  void _toggleTodoMark() {
    final text = _contentController.text;
    final selection = _contentController.selection;

    // 如果没有选中任何文本，使用光标位置
    final cursorPosition = selection.baseOffset;
    if (cursorPosition < 0) return;

    // 找到光标所在行的起始和结束位置
    int lineStart = text.lastIndexOf('\n', cursorPosition - 1) + 1;
    int lineEnd = text.indexOf('\n', cursorPosition);
    if (lineEnd == -1) lineEnd = text.length;

    // 获取当前行的文本
    final currentLine = text.substring(lineStart, lineEnd);

    String newLine;
    int newCursorPosition = cursorPosition;

    // 检查当前行是否已经有TODO标记
    if (currentLine.trimLeft().startsWith('- [ ]')) {
      // 如果有，则删除（包括后面的空格，总共6个字符："- [ ] "）
      final leadingSpaces = currentLine.length - currentLine.trimLeft().length;
      final trimmedContent = currentLine.trimLeft();
      // 检查 "- [ ]" 后面是否有空格
      final hasSpace = trimmedContent.length > 5 && trimmedContent[5] == ' ';
      final removeLength = hasSpace ? 6 : 5; // 如果有空格则删除6个字符，否则删除5个

      newLine = currentLine.substring(0, leadingSpaces) +
                currentLine.substring(leadingSpaces + removeLength);
      // 光标位置调整：如果光标在标记之后，需要向左移动相应字符数
      if (cursorPosition > lineStart + leadingSpaces) {
        newCursorPosition = cursorPosition - removeLength;
      }
    } else {
      // 如果没有，则在行首添加
      final leadingSpaces = currentLine.length - currentLine.trimLeft().length;
      newLine = '${currentLine.substring(0, leadingSpaces)}- [ ] ${currentLine.trimLeft()}';
      // 光标位置调整：向右移动6个字符（"- [ ] "）
      newCursorPosition = cursorPosition + 6;
    }

    // 构建新文本
    final newText = text.substring(0, lineStart) + newLine + text.substring(lineEnd);

    // 重新请求焦点，避免点击按钮后失去焦点
    _contentFocusNode.requestFocus();

    // 在下一帧更新文本和光标位置，确保焦点恢复后光标位置正确
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _contentController.value = TextEditingValue(
        text: newText,
        selection: TextSelection.collapsed(offset: newCursorPosition),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(_getTitle()),
      ),
      body: Column(
        children: [
          // 操作栏
          if (_currentTodo != null)
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Row(
                children: [
                  // 左侧按钮组：置顶
                  if (!_isCreateMode)
                    Container(
                      decoration: BoxDecoration(
                        color: const Color(0xFFF7F7F7),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: IconButton(
                        icon: Icon(
                          _currentTodo!.isTop ? Icons.push_pin : Icons.push_pin_outlined,
                          color: _currentTodo!.isTop ? Colors.orange[700] : Colors.grey[600],
                        ),
                        onPressed: () {
                          _onToggleTop(!_currentTodo!.isTop);
                        },
                        tooltip: _currentTodo!.isTop ? '取消置顶' : '置顶',
                      ),
                    ),
                  const SizedBox(width: 8),
                  // 中间按钮组：Markdown操作
                  Container(
                    decoration: BoxDecoration(
                      color: const Color(0xFFF7F7F7),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // TODO标记按钮
                        IconButton(
                          icon: Icon(
                            Icons.check_box_outlined,
                            color: !_isPreviewMode ? Colors.grey[700] : Colors.grey[400],
                          ),
                          onPressed: !_isPreviewMode ? _toggleTodoMark : null,
                          tooltip: '切换TODO标记',
                        ),
                      ],
                    ),
                  ),
                  const Spacer(),
                  // 右侧按钮组：星级、预览/编辑、删除
                  Container(
                    decoration: BoxDecoration(
                      color: const Color(0xFFF7F7F7),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // 关注按钮（创建模式下隐藏）
                        if (!_isCreateMode)
                          IconButton(
                            icon: Icon(
                              _currentTodo!.isFavorite ? Icons.favorite : Icons.favorite_border,
                              color: _currentTodo!.isFavorite ? Colors.red : Colors.grey[600],
                              size: 22,
                            ),
                            tooltip: _currentTodo!.isFavorite ? '取消关注' : '关注',
                            onPressed: _toggleFavorite,
                          ),
                        // 预览/编辑切换按钮
                        IconButton(
                          icon: Icon(
                            _isPreviewMode ? Icons.edit_outlined : Icons.preview_outlined,
                            color: Colors.grey[600],
                          ),
                          onPressed: () {
                            setState(() {
                              _isPreviewMode = !_isPreviewMode;
                            });
                          },
                          tooltip: _isPreviewMode ? '编辑' : '预览',
                        ),
                        // 删除按钮（创建模式下隐藏）
                        if (!_isCreateMode)
                          IconButton(
                            icon: Icon(
                              Icons.delete_outline,
                              color: Colors.red[400],
                            ),
                            onPressed: _onDelete,
                            tooltip: '删除',
                          ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          // 文本编辑/预览区域
          Expanded(
            child: (_isPreviewMode && !_isCreateMode)
                ? Markdown(
                    data: _contentController.text,
                    selectable: true,
                    padding: const EdgeInsets.all(24),
                    onTapLink: _handleLinkTap,
                    styleSheet: MarkdownStyleSheet(
                      // 基础文本样式 - 参考 markdown-classic
                      p: const TextStyle(
                        fontSize: 14,
                        height: 1.75,
                        color: Color(0xFF353535),
                        letterSpacing: 0.8,
                        wordSpacing: 0.8,
                      ),
                      // 标题样式
                      h1: const TextStyle(
                        fontSize: 22,
                        fontWeight: FontWeight.w300,
                        color: Color(0xFF2c3e50),
                        height: 1.3,
                      ),
                      h2: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w700,
                        color: Color(0xFF2c3e50),
                        height: 1.4,
                      ),
                      h3: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF34495e),
                        height: 1.4,
                      ),
                      h4: const TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF34495e),
                      ),
                      h5: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF34495e),
                      ),
                      h6: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF34495e),
                      ),
                      // H2边框装饰
                      h2Padding: const EdgeInsets.only(left: 10, top: 20, bottom: 10),
                      // 列表样式
                      listBullet: const TextStyle(
                        color: Color(0xFFf83929),
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                      ),
                      listBulletPadding: const EdgeInsets.only(right: 8),
                      // 链接样式
                      a: const TextStyle(
                        color: Color(0xFF373532),
                        decoration: TextDecoration.underline,
                        decorationColor: Color(0x66373532),
                      ),
                      // 强调样式
                      strong: const TextStyle(
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF353535),
                      ),
                      em: const TextStyle(
                        color: Color(0xFFf83929),
                        fontStyle: FontStyle.italic,
                      ),
                      // 引用样式
                      blockquote: const TextStyle(
                        color: Color(0xFF353535),
                        fontSize: 14,
                        height: 1.75,
                      ),
                      blockquoteDecoration: BoxDecoration(
                        color: const Color(0xFFf5f5f5),
                        borderRadius: BorderRadius.circular(13),
                      ),
                      blockquotePadding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
                      // 代码样式 - 行内代码
                      code: const TextStyle(
                        fontFamily: 'SFMono-Regular, Menlo, Consolas, monospace',
                        fontSize: 12,
                        color: Color(0xFFEB5757),
                        backgroundColor: Color(0x26878378),
                      ),
                      // 代码块样式
                      codeblockDecoration: BoxDecoration(
                        color: const Color(0xB3EEEEEE),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      codeblockPadding: const EdgeInsets.all(16),
                      // 水平分隔线
                      horizontalRuleDecoration: BoxDecoration(
                        border: Border(
                          top: BorderSide(
                            width: 2,
                            color: const Color(0xBFf83929),
                          ),
                        ),
                      ),
                      // 表格样式
                      tableHead: const TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                        color: Color(0xFF353535),
                      ),
                      tableBody: const TextStyle(
                        fontSize: 13,
                        color: Color(0xFF353535),
                      ),
                      tableBorder: TableBorder.all(
                        color: const Color(0xFFcccccc),
                        width: 1,
                      ),
                      tableCellsPadding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 8,
                      ),
                      // 图片边距和装饰
                      img: const TextStyle(height: 1.0),
                    ),
                  )
                : TextField(
                    controller: _contentController,
                    focusNode: _contentFocusNode,
                    style: const TextStyle(
                      fontSize: 16,
                      height: 1.6,
                    ),
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.all(24),
                    ),
                    maxLines: null,
                    expands: true,
                    textAlignVertical: TextAlignVertical.top,
                  ),
          ),
        ],
      ),
    );
  }
}
